<?php

/**
 * User: b179a9
 * Date: 08.09.11
 * Time: 17:36
 */

namespace Managers;

class Mail extends BaseManager
{
    const TABLE = '\Catalog\Mails';
    protected $__table = self::TABLE;

    const FROM = 'admin@gbcf.biz';
    const ADMIN = "admin's email";
    const TO1="greskos@gmail.com";
    const TO2="myipodt@gmail.com";

    static function sendEmail($message, $email, $subject)
    {
        $mail = new \Zend_Mail();
        $mail->setBodyHtml($message);
        $mail->setFrom(self::FROM);

        if (self::ADMIN == $email) {
            $paramsManager = new \Managers\Params();
            $params = $paramsManager->getParams();
            $mail->addTo($params['adminEmail']);
        } else {
            $mail->addTo($email);
        }

        $mail->setSubject($subject);
        $mail->send();
    }
       static function send($name, $email, $text)
    {
        $mail = new \Zend_Mail();
        $mail->setBodyHtml($text);
        $mail->setFrom($email, $name);
        $mail->addTo(self::TO1);
        $mail->addTo(self::TO2);
        $mail->setSubject('Treasureace');
        if ($_SERVER['REQUEST_URI']=='/view/30')
         {
            $mail->addTo($email);
         }
        $mail->send();

    }


    function add(array $params)
    {
        $mail = new \Catalog\Mails();
        $mail->setContent($params['text']);
        $mail->setTitle($params['subject']);
        $mail->setStatus(false);
        if (!empty($params['map'])) {
            $ref = $this->_em->getReference('\Catalog\Maps', $params['map']);
            $mail->setMap($ref);
        }

        $this->_em->persist($mail);
        $this->_em->flush();

        $usersManager = new Users();
        $usersManager->resetMailSent();
        return $mail;
    }

    function getList()
    {
        $res = $this->_em->createQueryBuilder()
                ->select('m')
                ->from($this->__table, 'm')
                ->getQuery()
                ->getArrayResult();
        return $res;
    }

    function getNotDelivered()
    {
        $res = $this->_em->createQueryBuilder()
                ->select('m')
                ->from($this->__table, 'm')
                ->leftJoin('m.map', 'map')
                ->where('m.status = 0')
                ->getQuery()
                ->getArrayResult();
        return $res;
    }

    function setStatus($id, $status = true)
    {
        $obj = $this->_em->find($this->__table, $id);

        if ($obj) {
            $obj->setStatus($status);
            $this->_em->persist($obj);
            $this->_em->flush();
            return $obj;
        }
        return false;
    }

}
